package org.menacheri.jetserver.app.impl;

import java.util.HashSet;
import java.util.Set;

import org.menacheri.jetserver.app.PlayerSession;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "player")
public class Player {
	@Id
	private Object id;
	private String username;
	private String password;
	private String email;

	/**
	 * One player can be connected to multiple games at the same time. Each
	 * session in this set defines a connection to a game. TODO, each player
	 * should not have multiple sessions to the same game.
	 */
	@Transient
	private Set<PlayerSession> playerSessions;

	public Player() {
		playerSessions = new HashSet<PlayerSession>();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Player other = (Player) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

	public synchronized boolean addSession(PlayerSession session) {
		return playerSessions.add(session);
	}

	public synchronized boolean removeSession(PlayerSession session) {
		boolean remove = playerSessions.remove(session);
		if (playerSessions.size() == 0) {
			logout(session);
		}
		return remove;
	}

	public synchronized void logout(PlayerSession session) {
		session.close();
		if (null != playerSessions) {
			playerSessions.remove(session);
		}
	}

	public Set<PlayerSession> getPlayerSessions() {
		return playerSessions;
	}

	public void setPlayerSessions(Set<PlayerSession> playerSessions) {
		this.playerSessions = playerSessions;
	}

	public Object getId() {
		return id;
	}

	public void setId(Object id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}
